package com.engr.springbooteasypoi.thread;

/**
 * 线程交互 wait notify notifyAll
 */
public class ThreadInteraction {

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            ThreadB b = new ThreadB();
            b.start();
            // 主线程拥有B对象上的锁，线程为了调用wait或notify方法，该线程必须是那个对象锁的拥有者
            synchronized (b) {

                try {
                    System.out.println("等待对象b完成计算....");
                    b.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("b对象计算的总和是: " + b.total);
            }
        }


    }
}

class ThreadB extends Thread {

    int total;

    @Override
    public void run() {
        synchronized (this) {
            for (int i = 0; i < 101; i++) {
                total += i;
            }
            // 完成计算了,唤醒在此对象监视器上等待的单个线程，在本例中线程A被唤醒
            //notify();
            //notifyAll();
            System.out.println("A Start()");
        }

    }
}